<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="阶段" prop="stage">
        <el-select v-model="queryParams.stage" placeholder="请选择阶段" style="width:240px" clearable>
          <el-option
            v-for="dict in sys_stage"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="重要性" prop="importance">
        <el-select v-model="queryParams.importance" placeholder="请选择重要性" style="width:240px" clearable>
          <el-option
            v-for="dict in ya_importance"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['teaching:interview:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teaching:interview:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teaching:interview:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['teaching:interview:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportEs"
          v-hasPermi="['teaching:interview:export']"
        >全量同步到es
        </el-button>
      </el-col>

      <el-col :span="4">
        <!-- 添加进度条 -->
        <el-progress
          v-if="exporting"
          :percentage="exportProgress"
          :format="p => p + '%'"
          status="success"
          style="margin-top: 10px;"
        ></el-progress>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="interviewList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="面试题ID" align="center" prop="id"/>
      <el-table-column label="阶段" align="center" prop="stage">
        <template #default="scope">
          <dict-tag :options="sys_stage" :value="scope.row.stage"/>
        </template>
      </el-table-column>
      <el-table-column label="面试题内容" align="center" prop="question"/>
      <el-table-column label="答案" align="center" prop="answer"/>
      <el-table-column label="知识点" align="center" prop="knowledgePoint"/>
      <el-table-column label="重要性" align="center" prop="importance">
        <template #default="scope">
          <dict-tag :options="ya_importance" :value="scope.row.importance"/>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['teaching:interview:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['teaching:interview:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改高频面试题对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="interviewRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="阶段" prop="stage">
          <el-select v-model="form.stage" placeholder="请选择阶段">
            <el-option
              v-for="dict in sys_stage"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="面试题" prop="question">
          <el-input v-model="form.question" placeholder="请输入面试题内容"/>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <el-input v-model="form.answer" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="知识点" prop="knowledgePoint">
          <el-input v-model="form.knowledgePoint" placeholder="请输入知识点"/>
        </el-form-item>
        <el-form-item label="重要性" prop="importance">
          <el-select v-model="form.importance" placeholder="请选择重要性，1-一般,2-重要,3-非常重要">
            <el-option
              v-for="dict in ya_importance"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Interview">
import {
  listInterview,
  getInterview,
  delInterview,
  addInterview,
  updateInterview,
  exportEs,
  queryExportEsProgress,
} from "@/api/teaching/interview"

import {EventSourcePolyfill} from 'event-source-polyfill'
import {getToken} from "@/utils/auth";
const {proxy} = getCurrentInstance()
const {sys_stage, ya_importance} = proxy.useDict('sys_stage', 'ya_importance')
const exportProgress = ref(0)
let sseSource = null
const exporting = ref(false)

const interviewList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stage: null,
    importance: null,
  },
  rules: {
    stage: [
      {required: true, message: "阶段不能为空", trigger: "change"}
    ],
    question: [
      {required: true, message: "面试题内容不能为空", trigger: "blur"}
    ],
    importance: [
      {required: true, message: "重要性，1-一般,2-重要,3-非常重要不能为空", trigger: "change"}
    ],
  }
})

const {queryParams, form, rules} = toRefs(data)

/** 查询高频面试题列表 */
function getList() {
  loading.value = true
  listInterview(queryParams.value).then(response => {
    interviewList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    stage: null,
    question: null,
    answer: null,
    knowledgePoint: null,
    importance: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("interviewRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加高频面试题"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getInterview(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改高频面试题"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["interviewRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateInterview(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addInterview(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除高频面试题编号为"' + _ids + '"的数据项？').then(function () {
    return delInterview(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('teaching/interview/export', {
    ...queryParams.value
  }, `interview_${new Date().getTime()}.xlsx`)
}

/** 导出es **/
function handleExportEs() {
  exporting.value = true;
  exportProgress.value = 0;
  proxy.$modal.confirm('是否全量同步到es?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    //ajax 请求服务器接口开始做全量同步
    exportEs().then(resp => {
      proxy.$modal.msgSuccess("导出任务已启动");
      // 连接SSE获取进度
      setTimeout(() => {
        connectProgressSSE();
      }, 3000);
    }).catch(err => {
      exporting.value = false;
      proxy.$modal.msgSuccess("同步失败");
    })
  }).catch(() => {
    proxy.$modal.msgError("已取消同步");
  });
}

// 连接SSE获取进度
function connectProgressSSE() {
  // 关闭已有连接
  if (sseSource) {
    sseSource.close();
  }
  // 创建新连接
  sseSource = new EventSourcePolyfill(import.meta.env.VITE_APP_BASE_API + "/teaching/interview/export/es/progress/sse", {headers: {'Authorization': `Bearer ${getToken()}`}});
  // 监听进度消息
  sseSource.addEventListener('progress', (event) => {
    exportProgress.value = JSON.parse(event.data);
    // 如果进度完成，关闭连接
    if (exportProgress.value >= 100) {
      exporting.value = false;
      sseSource.close();
      sseSource = null;
      proxy.$modal.msgSuccess("导出完毕")
    }
  });


  // 监听错误
  sseSource.onerror = () => {
    exporting.value = false;
    sseSource.close();
    sseSource = null;
    proxy.$modal.msgError("获取进度失败")
  };
}

getList()
</script>
